package com.lhl.log.config;

import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @className: LogInterceptor
 * @description: TODO 类描述
 * @author: king
 * @date: 2020-09-16 10:19
 **/
public class LogInterceptor extends HandlerInterceptorAdapter {
    private final String tracId = "tracId";
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                             Object o) throws Exception {
        String value = UUID.randomUUID().toString().replaceAll("-", "");
        MDC.put(tracId, value);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
        MDC.remove(tracId);
    }
}